package cn.tedu.csmall.server.exception.handler;

import cn.tedu.csmall.server.exception.ServiceException;
import cn.tedu.csmall.server.web.JsonResult;
import cn.tedu.csmall.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;


/**
 * @author lixin
 * @Date 2022/9/6
 * 统一异常处理类
 */
@Slf4j
@RestControllerAdvice //添加次注解的类中的注解方法会被作用于每一次请求
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e) {
        return JsonResult.fail(e);
    }
    @ExceptionHandler
    public JsonResult handleBindException(BindException e) {
        final List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
//        final StringBuilder builder = new StringBuilder();
//        for (FieldError fieldError : fieldErrors) {
//            builder.append(fieldError.getDefaultMessage());
//            builder.append(";");
//        }
        //StringJoiner(分隔符,前缀,后缀)
        final StringJoiner stringJoiner = new StringJoiner(";","~","~");
        for (FieldError fieldError : fieldErrors) {
            stringJoiner.add(fieldError.getDefaultMessage());
        }
        final String message = stringJoiner.toString();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e) {
        log.error("统一处理未明确异常：{},错误信息{}", e.getClass().getName(), e.getMessage());
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN, e.getMessage());
    }

}
